layui.config({
    version: '1593348928630' //为了更新 js 缓存，可忽略
    });

layui.use(['laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element', 'slider','form'], function(){
    var laydate = layui.laydate //日期
    , $ = layui.$
    , layer = layui.layer //弹层
    , table = layui.table //表格
    , element = layui.element
    , form = layui.form
    , getUrls = jsRoutes.controllers.admin.UsersController.getList()
    , indexUrls = jsRoutes.controllers.admin.UsersController.index()
    , permissionUrls = jsRoutes.controllers.admin.UsersController.updatePermission()
    , setGroupUrls = jsRoutes.controllers.admin.NasController.setGroupAsNasGroupId()
    , upwdUrls = jsRoutes.controllers.UsersController.pwdUpdated();

    var layid = location.hash.replace("#", '');
    console.log(layid);
    element.tabChange('accTabBrief', layid);
    accList(layid,{"name":"","active":""})
    //向世界问个好
    element.on('tab(accTabBrief)', function (data) {
        layer.msg('切到到了' + data.index + '：' + this.innerHTML);
        location.hash = this.getAttribute('lay-id');
        layid = location.hash.replace("#", '');
    accList(layid,{"name":""})
    });
    var csrfToken = $('[name="csrfToken"]').val();
   function accList(layid,data){
    if (layid=='users'){
        //执行一个 table 实例
            var demotable = table.render({
            elem: '#demoUsers'
            ,contentType: 'application/json'
            ,headers: {"Csrf-Token": csrfToken}
            ,method: getUrls.method
            , height: 550
            , url: getUrls.url + "?tab=user"//数据接口
            ,title: '用户表'
            ,page: true //开启分页
            ,toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , where:data
            ,cols: [[ //表头
            {type: 'checkbox', fixed: 'left'}
            ,{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
            ,{field: 'accid', title: 'accid', width:80, hide:true, fixed: 'left'}
            ,{field: 'company', title: '公司', width:130}
            ,{field: 'name', title: '用户名', width:130}
            ,{field: 'position', title: '职务', width: 130, sort: true}
            ,{field: 'email', title: 'Email', width:180, sort: true}
            ,{field: 'mobile', title: '手机号', width: 120, sort: true}
            ,{field: 'department', title: '部门', width: 80, sort: true}
             ,{field: 'active', title: '启用', width: 80, sort: true}
            ,{fixed: 'right', title: '操作', width: 200, align:'center', toolbar:  '#userBarDemo'}
            ]]
            });
        }
    if (layid=='groups'){
            //执行一个 table 实例
                var demotable = table.render({
                elem: '#demoGroups'
                ,contentType: 'application/json'
                ,headers: {"Csrf-Token": csrfToken}
                ,method: getUrls.method
                , height: 550
                , url: getUrls.url + '?tab=group' //数据接口
                ,title: '部门表'
                ,page: true //开启分页
                ,toolbar: '#userBarGroupsDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档

                ,where:data
                ,cols: [[ //表头
                {type: 'checkbox', fixed: 'left'}
                ,{field: 'id', title: 'ID', width:120, sort: true, fixed: 'left'}
                ,{field: 'company', title: '公司', width:130}
                ,{field: 'name', title: '部门', width:130}
                ,{field: 'parentid', title: '部门id', width: 120, sort: true}
                ,{field: 'nas_gid', title: 'nas_id', width:100, sort: true}
                ,{field: 'nas_group', title: 'nas组', width:120, sort: true}
                ,{field: 'nas_gname', title: 'nas组名', width: 120, sort: true}
                ,{fixed: 'right', title: '操作', width: 200, align:'center', toolbar: '#barDemo'}
                ]]
                });
            }
    if (layid=='permission'){
                    //执行一个 table 实例

                        var demotable = table.render({
                        elem:  '#demoPermission'
                        ,contentType: 'application/json'
                        ,headers: {"Csrf-Token": csrfToken}
                        ,method: getUrls.method
                        , height: 550
                        , url: getUrls.url + "?tab=permission"//数据接口
                        ,title: '用户表'
                        ,page: true //开启分页
                        ,toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
                        , where:data
                        ,cols: [[ //表头
                        {type: 'checkbox', fixed: 'left'}
                        ,{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
                        ,{field: 'name', title: '用户名', width:130}
                        ,{field: 'position', title: '职务', width: 130, sort: true}
                        ,{field: 'mobile', title: '手机号', width: 120, sort: true}
                         ,{field: 'active', title: '启用', width: 80, sort: true}
                         ,{field: 'permissions', title: '权限', width: 380, sort: true}
                        ,{fixed: 'right', title: '操作', align:'center', toolbar: '#permissionBarDemo'}
                        ]]
                        });
                    }
            }

    table.on('toolbar(testgroups)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id)
            , csdata = checkStatus.data //获取选中的数据
            , layEvent = obj.event;

        if (layEvent === 'changegroup') {
            layer.msg('修改用户组');

            var userArr = []
            var gid = form.val("jsonSetGroup").gid

            for (i = 0; i < csdata.length; i++) {
                userArr.push({ "id": csdata[i].id, "gid": gid });
            }

            $.post({
                url: setGroupUrls.url ,
                headers: {"Csrf-Token": csrfToken},
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(userArr),
                dataType: 'text',
                success: function (data) {
                    console.log(data);
                    alert("数据: \n" + data + "\n状态: " + status);
                    demotable.reload();
                }
            });
        }else if (layEvent  === 'add'){
          layer.msg('新增用户组');
          window.top.location.href = groupCreateUrls.url;
        }


    });

    //监听头工具栏事件
    table.on('toolbar(test)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id)
    ,data = checkStatus.data; //获取选中的数据
    switch(obj.event){
    case 'add':
    layer.msg('添加');
    break;
    case 'update':
    if(data.length === 0){
    layer.msg('请选择一行');
    } else if(data.length > 1){
    layer.msg('只能同时编辑一个');
    } else {
    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
    }
    break;
    case 'delete':
    if(data.length === 0){
    layer.msg('请选择一行');
    } else {
    layer.msg('删除');
    console.log(data)

    var userArr = []
    for (i=0;i<data.length;i++){
    userArr.push(data[i].id);
    }
    $.post({
        url: indexUrls.url,
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify({ option:"onoff",id:userArr}),
        dataType: 'text',
        success: function (data) {
        console.log(data);
        alert("数据: \n" + data + "\n状态: " + status);
        demotable.reload();
        }
    });

    }
    break;
    };
    });

    //监听行工具事件
    table.on('tool(testusers)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
    var data = obj.data //获得当前行数据
    ,layEvent = obj.event; //获得 lay-event 对应的值
    if(layEvent === 'edit'){
    layer.msg('重置密码');
    console.log(data)
    ///
    layer.open({
        type: 1
       , title: data.name
       , area: ['400px','200px']
       , shade: 0
       , content: $('.userBarPwdEdit')
       , btn: ['提交', '关闭']
       , yes: function (index, layero) {
         //按钮【按钮一】的回调
         console.log(index)
         var fdata = form.val("userBarPwdEditForm")
         //if (data.user!="") fdata.user="0"
         console.log(fdata)
         var load_index = layer.load(1, { time: 30 * 1000 });
         $.post({
           url: upwdUrls.url,
           contentType: 'application/json; charset=UTF-8',
           headers: {"Csrf-Token": csrfToken},
           data: JSON.stringify({ accid: data.accid, p1: fdata.p1,p2:fdata.p2}),
           //                 dataType: 'text',
           success: function (data) {
             console.log(data);
             layer.close(load_index);
             layer.msg("数据: \n" + data + "\n状态: " + status);
             //demotable.reload();
           }
         });
         layer.close(index);
       }
       , btn2: function (index, layero) {
         //按钮【按钮二】的回调
         //return false 开启该代码可禁止点击该按钮关闭
       }
       , cancel: function () {
         //右上角关闭回调
         //return false 开启该代码可禁止点击该按钮关闭
       }

     });
    } else if(layEvent === 'del'){
    layer.confirm('真的删除行么', function(index){
    layer.close(index);
    //向服务端发送删除指令
    console.log(data.id);
    var userArr = []
    userArr.push(data.id);
    $.post({
    url: postUrls.url,
    contentType: 'application/json',
    data: JSON.stringify({ option:"delete",id:userArr}),
    dataType: 'text',
    success: function (data) {
    console.log(data);
    alert("数据: \n" + data + "\n状态: " + status);
    obj.del(); //删除对应行（tr）的DOM结构

    }
    });


    });
    } else if(layEvent === 'edit'){
    layer.msg('编辑操作');
    console.log(data.id);
    }
    });

    table.on('toolbar(permissionusers)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
        ,data = checkStatus.data; //获取选中的数据
        switch(obj.event){
        case 'add':
        layer.msg('添加');
        break;
        case 'update':
        var userArr = []
        if(data.length === 0){
//            layer.msg('请选择一行或多行');
        } else {
        console.log(data)
        for (i=0;i<data.length;i++){
            userArr.push(data[i].id);
        }
        }
        layer.msg('更新 [id]：'+ userArr);
        permision(userArr);
        break;
        case 'delete':
        var userArr = []
        if(data.length === 0){
            layer.msg('请选择一行');
        } else {
            layer.msg('删除');
            console.log(data)
            for (i=0;i<data.length;i++){
                userArr.push(data[i].id);
            }
            layer.msg("删除 [id]：:"+ userArr)
        }

        break;
        };
        });

    function permision(userArr){
    $.post({
        url: permissionUrls.url,
        contentType: 'application/json',
        headers: {"Csrf-Token": csrfToken},
        data: JSON.stringify({ option:"permission",id:userArr}),
        dataType: 'text',
        success: function (data) {
        console.log(data);
        layer.msg("数据: \n" + data + "\n状态: " + status);
        }
        });
    }

    form.on('submit(formusers)', function (data) {
        layid = location.hash.replace("#", '');
        console.log(data)
        accList(layid,data.field);
        return false;
    });

    form.on('submit(formgroups)', function (data) {
        layid = location.hash.replace("#", '');
        accList(layid,data.field);
        return false;
    });

    form.on('submit(permissionusers)',function(data){
         layid = location.hash.replace("#", '');
         accList(layid,data.field);
         return false;
    });


});

